package cn.fboost.mtos.handler;

import cn.fboost.mtos.dto.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class RequestExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Response handler(Exception e) {
        if (e instanceof MethodArgumentNotValidException) {
            FieldError fieldError = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError();
            if (fieldError != null) {
                return Response.builder().failure().msg("服务器错误").data(fieldError.getDefaultMessage()).build();
            }
        }

        if (e instanceof BindException) {
            FieldError fieldError = ((BindException) e).getBindingResult().getFieldError();
            if (fieldError != null) {
                return Response.builder().failure().msg("服务器错误").data(fieldError.getDefaultMessage()).build();
            }
        }

        log.error(e.getMessage());
        e.printStackTrace();
        return Response.builder().failure().msg("服务器错误").data(e.getMessage()).build();
    }
}
